package com.testmanager.testmananger.quantitative.service;

import com.testmanager.testmananger.foundation.util.FlakeIdGenerator;
import com.testmanager.testmananger.quantitative.constants.Sign;
import com.testmanager.testmananger.quantitative.domain.DemandInfoEntity;
import com.testmanager.testmananger.quantitative.domain.WorkerEntity;
import com.testmanager.testmananger.quantitative.dto.DemandInfoDto;
import com.testmanager.testmananger.quantitative.mapper.DemandInfoMapper;
import com.testmanager.testmananger.quantitative.mapper.WorkerMapper;
import com.testmanager.testmananger.quantitative.repository.DemandInfoRepository;
import com.testmanager.testmananger.quantitative.repository.WorkerRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class DemandInfoService {
    
    @Autowired
    DemandInfoRepository demandInfoRepository;
    @Autowired
    WorkerRepository workerRepository;
    @Autowired
    WorkService workService;
    @Autowired
    FlakeIdGenerator flakeIdGenerator ;
    
    public DemandInfoDto getDemandInfo(long iterationId){
        DemandInfoEntity demandInfoEntity = demandInfoRepository.findByIterationId(iterationId);
        if (demandInfoEntity == null) return null;
        List<WorkerEntity> workerEntities = workerRepository.findWorkerEntitiesByOwnerNo(demandInfoEntity.getDemandNo());
        if (workerEntities.size() == 0){
            return DemandInfoMapper.toDemandInfoDto(demandInfoEntity, null);
        }
        return DemandInfoMapper.toDemandInfoDto(demandInfoEntity, WorkerMapper.toWorkerDto(workerEntities.get(0)));
    }
    @Transactional
    public DemandInfoDto saveDemandInfo(long iterationId,DemandInfoDto demandInfoDto ){
        log.info("保存需求信息：{},iterationId:{}",demandInfoDto,iterationId);
        if (demandInfoDto.getDemandNo() ==0) demandInfoDto.setDemandNo(flakeIdGenerator.newId());
        //写worker信息，写demand信息
        if (demandInfoDto.getWorker() != null){
          //  workerRepository.save(WorkerMapper.toWorkerEntity(demandInfoDto.getDemandNo(), demandInfoDto.getWorker()));
            workService.saveWorker(WorkerMapper.toWorkerEntity(demandInfoDto.getDemandNo(), demandInfoDto.getWorker()));
        }

         demandInfoRepository.save(DemandInfoMapper.toDemandInfoEntity(demandInfoDto, iterationId));
         return getDemandInfo(iterationId);
    }
    
}
